package com.learn.english.controller;

import com.learn.english.domain.R;
import com.learn.english.model.entity.Note;
import com.learn.english.service.INoteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/note")
public class NoteController {

    @Autowired
    private INoteService noteService;

    /**
     * 获取当前用户的笔记树形结构
     */
    @GetMapping("/tree")
    public R<List<Note>> getNoteTree(@RequestParam Integer userId) {
        if (userId == null) {
            return R.fail("用户ID不能为空");
        }
        List<Note> allNotes = noteService.listByUserId(userId);
        List<Note> tree = buildTree(allNotes, null);
        return R.ok(tree);
    }

    private List<Note> buildTree(List<Note> all, Integer parentId) {
        return all.stream()
                .filter(note -> {
                    Integer pid = note.getParentId();
                    return (parentId == null) ? (pid == null || pid == 0) : parentId.equals(pid);
                })
                .peek(note -> note.setChildren(buildTree(all, note.getId())))
                .collect(Collectors.toList());
    }

    @GetMapping("/{id}")
    public R<Note> getNoteDetail(@PathVariable Integer id) {
        if (id == null) return R.fail("ID不能为空");
        Note note = noteService.getById(id);
        if (note == null) return R.fail("笔记不存在");
        return R.ok(note);
    }

    @PostMapping("/add")
    public R<Note> addNote(@RequestBody Note note) {
        if (note.getUserId() == null) return R.fail("用户ID不能为空");
        if (note.getParentId() != null && note.getParentId() == 0) {
            note.setParentId(null);
        }
        noteService.save(note);
        return R.ok(noteService.getById(note.getId()));
    }

    @PostMapping("/update")
    public R<String> updateNote(@RequestBody Note note) {
        if (note.getId() == null) return R.fail("笔记ID不能为空");
        if (note.getParentId() != null && note.getParentId() == 0) {
            note.setParentId(null);
        }
        boolean updated = noteService.updateById(note);
        return updated ? R.ok("更新成功") : R.fail("更新失败");
    }

    @GetMapping("/delete/{id}")
    public R<String> deleteNote(@PathVariable Integer id) {
        if (id == null) return R.fail("ID不能为空");
        List<Integer> idsToDelete = collectAllDescendantIds(id);
        noteService.removeByIds(idsToDelete);
        return R.ok("删除成功");
    }

    private List<Integer> collectAllDescendantIds(Integer rootId) {
        List<Note> allNotes = noteService.listAll(); // 获取所有笔记用于构建树
        Map<Integer, List<Integer>> parentToChildren = new HashMap<>();
        for (Note note : allNotes) {
            parentToChildren.computeIfAbsent(note.getParentId(), k -> new ArrayList<>()).add(note.getId());
        }

        List<Integer> result = new ArrayList<>();
        Queue<Integer> queue = new LinkedList<>();
        queue.offer(rootId);

        while (!queue.isEmpty()) {
            Integer current = queue.poll();
            result.add(current);
            List<Integer> children = parentToChildren.get(current);
            if (children != null) queue.addAll(children);
        }
        return result;
    }

    // —————— 兼容分页列表（可选） ——————
    @GetMapping("/list")
    public R<Map<String, Object>> list(
            @RequestParam(required = false) String title,
            @RequestParam(required = false) Integer userId,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {

        int offset = (pageNum - 1) * pageSize;
        List<Note> records = noteService.listWithPagination(userId, title, offset, pageSize);
        long total = noteService.count(userId, title);

        Map<String, Object> pageResult = new HashMap<>();
        pageResult.put("records", records);
        pageResult.put("total", total);
        pageResult.put("pageNum", pageNum);
        pageResult.put("pageSize", pageSize);

        return R.ok(pageResult);
    }

    @PostMapping("/batch")
    public R<String> batchDelete(@RequestBody List<Integer> ids) {
        noteService.removeByIds(ids);
        return R.ok("批量删除成功");
    }
}